package com.chao.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/17
 */
public class LockPc {

    public static void main(String[] args) {
        Resource2 resource2 = new Resource2();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                resource2.incrementOne();
            }
        },"A").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                resource2.decrementOne();
            }
        },"B").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                resource2.incrementOne();
            }
        },"C").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                resource2.decrementOne();
            }
        },"D").start();
    }
}

class Resource2{

    private int num = 0;

    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public void incrementOne() {
        lock.lock();
        try {
            while (num != 0){
                //等待
                condition.await();
            }
            num ++;
            System.out.println(Thread.currentThread().getName() + "==>" +num);
            //通知其他线程
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void decrementOne() {
        lock.lock();
        try {
            while (num == 0){
                //等待
                condition.await();
            }
            num --;
            System.out.println(Thread.currentThread().getName() + "==>" +num);
            //通知
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
